from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
"""
前端需要生成一个uuid,传递给我们后台,我们后台生成图片 和包图片验证码内容保存到redis中


# 1.接收参数
# 2.生成图片和记录验证码(保存到redis中)
# 3.返回响应


GET     /verifications/imagecodes/(?P<image_code_id>.+)/

"""
# APIView
#GenericAPIView                     列表,视图做了通用支持,一般和mixin配置使用
#ListAPIView,RetrieveAPIView
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from rest_framework.response import Response

class RegisterImageCodeView(APIView):


    def get(self,request,image_code_id):

        # 1.生成图片
        text,image = captcha.generate_captcha()
        # 2记录验证码(保存到redis中)
        redis_conn = get_redis_connection('code')
        from . import constants
        redis_conn.setex('img_%s'%image_code_id,constants.IMAGE_CODE_EXPIRE_TIME,text)

        # 3.返回响应
        # return HttpResponse(image,content_type='application/json')   错误的
        return HttpResponse(image,content_type='image/jpeg')
        # return Response(image,content_type='image/jpeg')  不可以的

"""
用户在点击获取短信验证码的时候,前端应该将 手机号,图片验证码内容和 uuid发送给后端

# 1.接收参数
# 2.校验参数
# 3.生成短信验证码内容
# 4.发送短信
# 5.返回响应

GET        verifications/smscodes/ mobile/text/uuid/
GET        verifications/smscodes/?mobile=xxx&text=xxx&uuid=xxxx

GET        /verifications/smscodes/(?P<mobile>1[345789]\d{9})/?text=xxxx & image_code_id=xxxx


"""
# APIView
#GenericAPIView                     列表,视图做了通用支持,一般和mixin配置使用
#ListAPIView,RetrieveAPIView
from .serializers import RegisterSmscodeSerializer
from random import randint
from libs.yuntongxun.sms import CCP

class RegisterSmscodeView(APIView):

    def get(self,request,mobile):
        # 1.接收参数
        params = request.query_params
        # 2.校验参数 -- 序列化器
        # text = params.get('text')
        # image_code_id = params.get('image_code_id')
        # if not all([text,image_code_id]):
        #     pass
        #
        # pass
        serializer = RegisterSmscodeSerializer(data=params)
        #
        serializer.is_valid(raise_exception=True)
        #
        # # 3.生成短信验证码内容
        sms_code = '%06d'%randint(0,999999)
        #
        redis_conn = get_redis_connection('code')
        redis_conn.setex('sms_%s'%mobile,300,sms_code)
        # # 4.发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        #
        from celery_tasks.sms.tasks import send_sms_code
        #
        # # delay 方法的参数 和 send_sms_code 的参数一一对应
        send_sms_code.delay(mobile,sms_code)
        #
        # # 5.返回响应
        return Response({'msg':'ok'})
